package com.egdigital.allzic.data.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.egdigital.allzic.data.object.Song;

public class JsonParserSong {

	// log
	private static final String		TAG			= JsonParserSong.class.getSimpleName();
	// data
	private static final String		TAG_ARTISTE	= "artist";
	private static final String		TAG_TITLE	= "title";
	private static final String		TAG_COVER	= "cover";
	private static final String		TAG_ONAIR	= "onair";
	private RequestQueue			mRequestQueue;
	private static JsonParserSong	mJsonParser;
	private JSONArray				mJsonArray	= null;
	private JsonCallBack			mJsonCallback;

	public static JsonParserSong getInstance() {
		if (mJsonParser == null) {
			return new JsonParserSong();
		} else {
			return mJsonParser;
		}
	}

	public void initAndStartRequestQueue() {
		mRequestQueue = VolleyManager.getRequestQueue();
		mRequestQueue.start();
	}

	public void stopRequestQueue() {
		mRequestQueue.stop();
	}

	public void extractJsonObjectData(String url) {
		JsonArrayRequest request = new JsonArrayRequest(url, createMyReqSuccessListener(), createMyReqErrorListener());
		request.setTag(this);
		mRequestQueue.add(request);
	}

	protected Response.Listener<JSONArray> createMyReqSuccessListener() {
		return new Response.Listener<JSONArray>() {

			public void onResponse(JSONArray jsonArray) {
				List<Song> list = new ArrayList<Song>();
				try {
					mJsonArray = jsonArray;
					for (int i = 0; i < mJsonArray.length(); i++) {
						mJsonCallback.downloadPercent(((i + 1) * 100) / mJsonArray.length());
						JSONObject jsonObject = mJsonArray.getJSONObject(i);
						Song song = new Song(jsonObject.get(TAG_ARTISTE).toString(), jsonObject.get(TAG_TITLE).toString(), jsonObject.get(TAG_COVER).toString(), jsonObject.get(TAG_ONAIR).toString());
						if (song.getmCover() != null && !song.getmCover().isEmpty()) { // add only if there is a cover
							list.add(song);
						}
					}
				} catch (Exception ex) {
				}
				mJsonCallback.downloadCompleted(list);
			}
		};
	}

	protected Response.ErrorListener createMyReqErrorListener() {
		return new Response.ErrorListener() {

			public void onErrorResponse(VolleyError error) {
				mJsonCallback.downloadEndedWithError(error);
			}
		};
	}

	public void setJsonCallBack(JsonCallBack callback) {
		mJsonCallback = callback;
	}
}
